<template>
	<view class="dispatchMaterial">
		<!-- 资源调度 --- 材料选择 -->
		<view class="device">
			<view class="leftBox">
				<view class="stationName" @click="show = true"  v-if="!obj.stationName">
					请选择基地
				</view>
				<view class="stationName stationNameActive" @click="show = true"  v-else>
					{{ obj.stationName }}
				</view>
				<view class="device-type">
					<view class="item" v-for="item in materialTypeList" :key="item.id" :class="{active: currentIndex === item.id}" @click="getSwitch(item)">{{ item.name }}</view>
				</view>
			</view>
			<view class="rightBox">
				<u--input
					prefixIcon="search"
					prefixIconStyle="font-size: 26px;color: #909399"
					class="input"
				   placeholder="请输入材料名称"
				   clearable
				   v-model="materialeName"
				   @change="materialNameChange"
				 ></u--input>
				 
				<view class="uniCollapse">
					<uni-collapse class="collapse">
						<uni-collapse-item  title-border="show" v-for="item in materialNameList" :key="item.name" :title="item.name">
							<template v-slot:title>
								<view class="collapse-title">
									<view class="left">
										{{ item.name }}
									</view>
									<view class="right">
										{{ item.totalNum }}
									</view>
								</view>
							</template>
							<view class="coll" v-for="(value,key) in item.children" :key="key">
								<view class="coll-item">
									<view class="name">规格型号： </view>
									<view class="value">{{ value.specificationModel }}</view>
								</view>
								<view class="coll-item">
									<view class="name">所属基地： </view>
									<view class="value">{{ value.stationName }}</view>
								</view>
								<view class="coll-item">
									<view class="name">库存： </view>
									<view class="value">{{ value.num }}{{ value.unit }}</view>
								</view>
								<view class="coll-item" v-if="!isRehearsal">
									<view class="name">出库： </view>
									<view class="value">
										<u-number-box :min="0" :max="Number(value.num) + Number(value.costNum)" v-model="value.costNum"  @change="(cur)=>inputNumberChange(value,cur.value)" :disabled="isShowInputNumber"></u-number-box>
									</view> {{ value.unit }}
								</view>
								<view class="coll-item" v-else>
									<view class="name">出库： </view>
									<view class="value">
										<u-number-box  :min="0" :max="value.num" v-model="value.costNum"  @change="(cur)=>inputNumberChange(value,cur.value)" :disabled="isShowInputNumber"></u-number-box>
									</view> {{ value.unit }}
								</view>
							</view>
						</uni-collapse-item>
					</uni-collapse>
				</view>
			</view>
		</view>
		
		<u-picker
			:show="show" 
			:columns="stationColumns"
			keyName="name"
			:closeOnClickOverlay="true"
			@confirm="stationConfirm" 
			@cancel="stationCancel">
		</u-picker>
	</view>
</template>

<script>
	import { getDeviceType, material_getListByDeviceTypeIdNoProjectId, getMaterialList, getShoppingCartMaterialList, getShoppingCartBatchDelete, getShoppingCartBatchSave } from "@/api/emergency/emergencyDispatch.js";
	import uniCollapse from "./uni-collapse/components/uni-collapse/uni-collapse.vue";
	export default {
		name: "dispatchMaterial",
		components: {
			uniCollapse
		},
		props: {
			stationList:{
				type: Array,
				default: ()=>[],
				required: true,
			},
			eventId: {
				type: Number,
				default: null,
				required: true,
			}
		},
		data() {
			return {
				show: false,
				materialTypeList: [],   // 材料类型列表
				materialNameList: [],          // 材料名称列表
				currentIndex: -1,
				stationColumns: [],    // 渲染的基地数据
				obj: {
					stationName: "",    // 选中的基地名称
					stationIds: [],     // 选中的基地id
				},
				deviceTypeIds: [],      // 选中的材料类型下, 所有的材料名称id
				materialeName: null,         // 材料名称模糊搜索
				isShowInputNumber: false,    // 在发送请求就 不允许再次发送请求
				isRehearsal:false
			}
		},
		mounted() {
			// stationList 父组件传递过来的基地数据
			// 格式化基地数据
			let list = JSON.parse(JSON.stringify(this.stationList))
			let test = uni.getStorageSync('isYanLian')
			console.log(test,'testwww222')
			if(test == 1) {
				this.isRehearsal = true
			}
			this.stationColumns = [list]
			this.getMaterialType()
			this.getMaterialList()
		},
		methods: {
			// 获取材料类型数据
			async getMaterialType(){
				let res = await getDeviceType({name: "", ex1: "material"})
				this.tempDeviceList = res.result
				// 只获取层级为2 的材料类型
				this.materialTypeList =  [{id: -1, name: "全部"},...res.result.filter(item => item.treeLevel === 2)]
			},
			
			// 获取设备列表数据
			async getMaterialList(isData){
				let _data = {
					eventId: this.eventId,
					stationIds: this.obj.stationIds,
					deviceTypeIds: this.deviceTypeIds,
					name: this.materialeName,
					typeIds:[102,104]
				}
				let res = await material_getListByDeviceTypeIdNoProjectId(_data)
				this.tempMaterialData = res.result
				// 第一次 可以使用购物车中的数据 getEventShoppingCartList 接口做渲染(渲染到页面上)
				// 后续 使用 getShoppingCartMaterialList 接口 做数据 删除 保存
				await this.getSelectMaterial(isData)
			},
			
			// 获取选中的材料
			async getSelectMaterial(isData){
				// 获取设备选中数据
				let mater2 = await getShoppingCartMaterialList({eventId: this.eventId})
				this.tempMaterialList = JSON.parse(JSON.stringify(mater2.result))
				let noExistList=[];//购物车与现有库存不重复的列表
				let cartMap={};// 购物车 唯一key 和出库量对应map
				let cartNoExistList=[]// 购物车与现有库存不存在key(去重)

				// 根据基地 过滤
				let tempList = mater2.result.filter(item=> {
					// 判断 是否有基地 id
					if(this.obj.stationIds && this.obj.stationIds.length > 0){
						return this.obj.stationIds.find((value)=> value === item.stationId)
					}else{
						return true
					}
				})

				// 根据材料类型 设备名称 过滤
				let tempList2 = tempList.filter(item=> {
					// 判断 是否有基地 id
					if(this.deviceTypeIds && this.deviceTypeIds.length > 0){
						return this.deviceTypeIds.includes(item.subDeviceTypeId)
					}else{
						return true
					}
				})
				
				// 根据模糊搜索过滤
				let tempList3 = tempList2.filter(item=> {
					// 判断 this.materialeName 是否有值
					if(this.materialeName){
						return (item.name).includes(this.materialeName)
					}else{
						return true
					}
				})
				tempList3.forEach(value=>{
					let key=value.name+value.stationName+value.specificationModel;//名称+基地+规格型号
					let itemNum=cartMap[key];
					if(!itemNum){
						itemNum=value.costNum
					}else{
						itemNum+=value.costNum
					}
					cartMap[key]=itemNum;
					let b=false;//购物车和库存列表是否重合
					this.tempMaterialData.forEach(item=>{
						if(item.name === value.name && item.stationName === value.stationName && item.specificationModel === value.specificationModel){
							value.num = value.num + item.num 
							value.costNum = value.costNum + item.costNum
							value.totalNum = ((value.totalNum * 1000) + (item.totalNum * 1000)) / 1000
							b=true;
						}
					})
					if(!b){
						value.totalNum = ((value.num * 1000) + (value.costNum * 1000)) / 1000
						noExistList.push(value);
						if(!cartNoExistList.includes(key)){
							cartNoExistList.push(key);
						}
					}
				})
				this.tempMaterialData = [...noExistList, ...this.tempMaterialData]
				// 处理数据, 返回一个数组 数组第一项是 一个对象, 第二项是个数组(格式化好的)
				let temp = this.getMaterialArray(this.tempMaterialData)
				this.tableData2 = temp[1]

				for (let index = 0; index < this.tableData2.length; index++) {
					let keyIndex= this.tableData2[index].name+this.tableData2[index].stationName+this.tableData2[index].specificationModel;
					
					this.tableData2[index].costNum=cartMap[keyIndex] ? cartMap[keyIndex] : 0; //购物车的出库数量
					if(cartNoExistList.length ==0 || !cartNoExistList.includes(keyIndex)){//购物车和库存列表是否重合
						// this.tableData2[index].num+= cartMap[keyIndex]?cartMap[keyIndex]:0;//库存数量+购物车出库数量
					}
				}
				
				// 按照 基地名称排序 基地名称相同, 按照 材料名称排序, 材料名称相同 按照规格型号排序
				this.tableData2.sort(function(val, item){
					if(val.stationName !== item.stationName){
						return val.stationName.localeCompare(item.stationName, "zh-CN")
					}
				
					if(val.name !== item.name){
						return val.name.localeCompare(item.name, "zh-CN")
					}
					return (val.specificationModel || "").localeCompare((item.specificationModel || ""), "zh-CN")
				})
				
				let sList = this.arrayFilter(this.tableData2, 'name')
				console.log(sList, '----');
				if(!isData){
					this.materialNameList = JSON.parse(JSON.stringify(sList))
					
				}
				this.materialNameList = this.materialNameList.map(item => ({...item, totalNum: item.totalNum ? item.totalNum : ((item.num * 1000) + (item.costNum * 1000)) / 1000} ));
				this.tempObj = temp[0]
			},
			
			// 切换材料类型 选中
			getSwitch(item){
				this.currentIndex = item.id
				
				// 当选中的不是全部时, 过滤出点击的设备类型下, 所有子集设备名称id
				if(this.currentIndex !== -1){
					this.deviceTypeIds = this.tempDeviceList.filter(item=>item.parentId === this.currentIndex).map(value=>value.id)
					this.getMaterialList()
				}else{
					this.deviceTypeIds = []
					this.getMaterialList()
				}
			},
			
			// 搜索材料名称change事件
			materialNameChange(val){
				if(val.trim() === ""){
					this.materialeName = null
				}
				this.getMaterialList()
			},
			
			// 计数器, change 事件
			async inputNumberChange(val,cur){
				console.log(val,cur,'cur');
				if(this.isShowInputNumber){
					return
				}
				this.isShowInputNumber = true
				let obj = {
					name: val.name,
					costNum: cur,
					stationName: val.stationName,
					specificationModel: val.specificationModel,
				}
				 // 先获取已经保存的 eventCostId
				let ids = this.tempMaterialList.filter(item=>obj.name === item.name && obj.stationName === item.stationName && obj.specificationModel === item.specificationModel).map(item=>item.eventCostId)
				// 把保存的数据先先删除掉
				if(ids.length  > 0){
					let res = await getShoppingCartBatchDelete(ids)
					await this.getMaterialList(true)
				}
	
				let str = obj.stationName + '-' + obj.name + "-" + obj.specificationModel
				let list = this.sumArray2(this.tempObj[str], obj.costNum, "num")
				console.log(list,'-----')
				console.log(this.tempObj[str],obj.costNum);
				let arr = []
				list.forEach(item=>{
					console.error(item, 'item303');
					if(item && item.num > 0){
						let obj = {
							itemId: item.id,
							type: "material",
							num: item.num,
							eventId: this.eventId,
						}
						arr.push(obj)
					}
				})
				// 再保存数据
				if(arr.length > 0){
					let res2 = await getShoppingCartBatchSave(arr)
				}
				await this.getMaterialList()
				// 调用购物车列表接口, 刷新 购物车数量
				await this.$emit("shoppingList")
				this.isShowInputNumber = false
			},
			
			// 基地 confirm 事件
			stationConfirm(val){
				this.show = false
				// 保存 基地名称 基地id
				this.obj.stationName = val.value[0].name
				this.obj.stationIds = [val.value[0].id]
				this.getMaterialList()
			},
			
			// 基地 cancel 事件
			stationCancel(){
				// 取消选择基地  基地名称 基地id 重置
				this.show = false
				this.obj.stationName = ""
				this.obj.stationIds = []
				this.getMaterialList()
			},
			
			getMaterialArray(newArr){
				let list = JSON.parse(JSON.stringify(newArr))
				let obj = {}
				for(let i = 0;i < list.length;i++) {
					let item = list[i]
					let str = item.stationName + '-' + item.name + "-" + item.specificationModel
					if(obj[str]){   
						obj[str].push(item)
					}else{
						obj[str] = []
						obj[str].push(item)
					}
				}

				let newList = []
				for (const key in obj) {
					let arr = obj[key]
					let num = 0
					for(let i = 0;i < arr.length;i++) {
						num = ((num * 1000) + (arr[i].num * 1000)) / 1000
					}
					let temp = {
						stationName: arr[0].stationName,
						name:  arr[0].name,
						specificationModel: arr[0].specificationModel,
						num: num,
						unit: arr[0].unit || "",
						costNum: 0,
						totalNum: arr[0].totalNum,
					}
					newList.push(temp)
				}
				return [obj, newList]
			},
			
			/**
			* @description:  list 数组根据 stationName分组 num统计数量
			* @param {type}  list: 需要处理的数组  (原数组)
			* @param {type}  stationName: 用于判断相同的键名 
			* @return:       返回值: 数组
			*/
			arrayFilter(list, stationName){
				console.log(list,'lsit00000');
				let obj = {}
				let newList = []
				for (let i = 0; i < list.length; i++) {
					let item = list[i]
					let str = item[stationName]
					if(obj[str]){
						obj[str].push(item)
					}else{
						obj[str]=[]
						obj[str].push(item)
					}
				}
				// 对象转数组
				for (let key in obj) {
					let value = obj[key]
					let totalNum = 0
					let unit = ""
					value.forEach(item=>{
						totalNum = ((totalNum * 1000) + (item.num * 1000)) / 1000
						console.log(totalNum,item.num, '402total');
						unit = item.unit
					})
					let newkey = {name: key, totalNum:totalNum+unit, children: value}
					newList.push(newkey)
				}
				return newList
			},
			    /**
			     * @description: list: 原数组,   initialValue: 计算到的值(数字)  keyName: 要计算的值(对象的key)
			     * @param {type}
			     * @return:
			     */
			    sumArray2(list, initialValue, keyName) {
			      let sum = 0
			      let obj = {
			        find: null,
			        index: null
			      }
			      for (let i = 0; i < list.length; i++) {
			        let item = list[i]
			        sum += item[keyName]
			        if (sum >= initialValue) {
			          obj.find = item
			          obj.find.num = initialValue - (sum - item[keyName])
			          obj.index = i
			          break
			        }
			      }
			      return [...list.slice(0, obj.index), obj.find]
			    }
		}
	}
</script>

<style lang="scss" scoped>
	.dispatchMaterial{
		height: 100%;
		background-color: #fff;
		.device{
			display: flex;
			padding-top: 10rpx;
			height: 100%;
			box-sizing: border-box;
			
			.leftBox{
				width: 250rpx;
				height: 100%;
				.stationName{
					height: 90rpx;
					text-align: center;
					line-height: 90rpx;
					color: #bbb;
					border: 2rpx solid #E2E5ED;
					cursor: pointer;
					margin-bottom: 20rpx;
					overflow: hidden; //超出的文本隐藏
					text-overflow: ellipsis; //溢出用省略号显示
					white-space: nowrap; //溢出则不换行
				}
				.stationNameActive{
					background-color: #2f80ed;
					border: none;
					color: #fff;
				}
				
				.device-type{
					font-weight: 600;
					font-size: 32rpx;
					text-align: center;
					background-color: #f5f7fa;
					padding-top: 15rpx;
					height: calc(100% - 120rpx);
					box-sizing: border-box;
					.item{
						height: 80rpx;
						line-height: 80rpx;
						font-family: Noto Sans Thai UI-Medium, Noto Sans Thai UI;
						color: #6A819E;
						cursor: pointer;
					}
					.active{
						color: #2f80ed;
						font-weight: 600;
					}
				}
				
			}
			.rightBox{
				flex: 1;
				height: 100%;
				width: calc(100% - 250px);
				padding-right: 30rpx;
				padding-left: 15rpx;
				box-sizing: border-box;
				overflow: auto;
				.input{
					width: 400rpx;
					height: 64rpx;
					margin-bottom: 20rpx;
				}
				.collapse{
					.coll{
						position: relative;
						margin-bottom: 20rpx;
						padding-bottom: 20rpx;
						border-bottom: 2rpx solid #E2E5ED;
						.coll-item{
							margin-top: 20rpx;
							display: flex;
							align-items: center;
							
							.name{
								margin-left: 25rpx;
							}
							.value {
								max-width: 240rpx;
								overflow: hidden;
								white-space: nowrap;
								text-overflow: ellipsis;
							}
						}
						.checkbox{
							position: absolute;
							top: 10rpx;
							right: 20rpx;
						}
					}
				}
			}
		}
	}
	::v-deep .uni-numbox__value{
		background-color: #fff !important;
		border: 2rpx solid #E2E5ED;
		margin: 0;
	}
</style>